<?php

namespace app\model;

use think\facade\Db;
use think\Model;

class ProductAttributesModel extends Model {

    protected $table ="product_attributes";

    protected $pk = 'product_attribute_id';

    private $cacheKey="product:attribute:id:";

    private $cacheTime=5184000;

    public function getInfo($id){
        $cacheKey = $this->cacheKey.$id;
        $redisModel = new RedisModel();
        $info = $redisModel->get($cacheKey);
        if($info){
            $info =  json_decode($info,true);
        }else{
            $info = Db::name('product_attributes')->find($id);
            $redisModel->set($cacheKey,json_encode($info,256),$this->cacheTime);
        }
        return $info;
    }


    /*
     * 获取商品属性
     * */
    public function getProductAttributes($product_id){

        $where =[];

        $where[] = ["product_id","=",$product_id];

        $info =  Db::name('product_attributes')->field("product_attribute_id")->where($where)->find();

        return $this->getInfo($info["product_attribute_id"]);
    }


    /*
  * 添加物流
  * */
    public function addOne($data){
        return Db::name('product_attributes')->insertGetId($data);
    }

    /*
 * 删除商品
 * */
    public function delAllProductAttributes($product_id){
        $where =[];
        $where[] = ["product_id","=",$product_id];
        return $this->delAll($where);
    }


    /*
     * 删除操作
     * */
    public function delAll($where){
        return Db::name('product_attributes')->where($where)->delete();
    }



    /*
     * 删除指定商品的缓存
     **/

    public function delProductAttributesCache($product_id){
        $where =[];
        $where[] = ["product_id","=",$product_id];
        $list = Db::name('product_attributes')->field("product_attribute_id")->where($where)->select();
        if($list){
            $redisModel = new RedisModel();
            foreach($list as $item){
                $redisModel->delete($this->cacheKey.$item["product_attribute_id"]);
            }
        }
    }


    /*
   * 删除全部商品的缓存
   **/

    public function delAllProductAttributesCache(){
        $redisModel = new RedisModel();
        $redisModel->deleteAll($this->cacheKey);
    }
}